/*
 * 说明：1.tools工具第一次重构时，页面还没有出来，所以可读性和抽象力度都很差。有时间会重构这一块。
 *      2.模块式之后最好都用命名函数表达式，不过由于要兼容IE8，不知道这种对象字面值写了之后会不会在IE8下有问题，所以就没有写。这会导致错误堆栈信息显示不是很明显。可以考虑在调试的时候加上。
 *      3.对于模块模式这里应该用更好的一种方式，可以将私有变量彻底隐藏。现在这种通过加__的是一种临时方案。有机会重构掉
 */
/*
 *  工具类
 */
var tools = {
    //    __currentRemarkObj: null
    //    ,
    getDropDownCallBack: function (target, func) {
        return function (obj, data) {
            $('#' + target).val(data.Value);
            if (func)
                func(obj, data);
            return true;
        };
    },
    getCarBrandCallBack: function () {
        if (!arguments || arguments.length === 0) return undefined;
        var o1 = arguments[0], o2 = arguments[1], o3 = arguments[2], o4 = arguments[3], o5 = arguments[4], o6 = arguments[5], o7 = arguments[6], o8 = arguments[7];
        return function (obj, data) {
            //选中品牌后,将车型数据先恢复到默认
            $("#" + o1).val("-1");
            $("#" + o2).val("全部车型");
            $("#" + o3).text("全部车型");
            selectData[o4] = [];

            //tools.getCarSerialsCallBack(o5, o6, o7, o8, '', true)();
            $("#" + o5).val("-1");
            $("#" + o6).val("全部车款");
            $("#" + o7).text("全部车款");
            selectData[o8] = [];

            //加载车型数据
            DropDownInfo.AjaxLoadCarSerialsInfo(data.Value);
        }
    },
    getCarSerialsCallBack: function () {
        if (!arguments || arguments.length === 0) return undefined;
        var o1 = arguments[0], o2 = arguments[1], o3 = arguments[2], o4 = arguments[3], o5 = arguments[4], o6 = arguments[5];
        return function (obj, data) {
            //初始化车款数据
            $("#" + o1).val("-1");
            $("#" + o2).val("全部车款");
            $("#" + o3).text("全部车款");
            selectData[o4] = [];
            if (!o6) {
                $("#" + o5).val(data.Text);
                DropDownInfo.AjaxLoadCarInfo(data.Value);
            }
        }
    },
    InitFunc: function (target, falseCallback, trueCallback) {
        var obj = $("#" + target);
        if (obj.val() === '-1' || !obj.val()) {
            if (trueCallback)
                trueCallback(obj);
            else {
                obj.text("全部");
                obj.val("-1");
            }
        } else {
            if (falseCallback)
                falseCallback();
        }
    },
    setCallbackMethods: function (funcArry) {
        if (funcArry) {
            for (var i = 0, l = funcArry.length; i < l; i++) {
                tools.setCallbackMethod(funcArry[i]);
            }
        }
    },
    setCallbackMethod: function (fun) {
        if (fun)
            window.Sys.WebForms.PageRequestManager.getInstance().add_endRequest(fun);
    },
    initDefaultText: function (valueTarget, dataList, setTextTarget) {
        if (!arguments || arguments.length === 0) return;
        var value = $("#" + valueTarget).val()
        , list = selectData[dataList];
        if (!list || list.length === 0) return;
        for (var item in list) {
            if (list[item].Value == $.trim(value)) {
                $("#" + setTextTarget).text(list[item].Text);
                break;
            }
        }
    }
    ,
    changeCur: function () {
        $('.h1_a').each(function () {
            if (window.location.href.indexOf($(this).attr('href')) > -1) {
                $(this).addClass('h1_a_cur');
            } else {
                $(this).removeClass('h1_a_cur');
            }
        });
    },
    SetUpDown: function (search, fn) {
        var search = $(search);
        if (search.hasClass("up")) {
            search.removeClass("up");
            search.addClass("down");
        } else {
            search.addClass("up");
            search.removeClass("down");
        }
        if (fn)
            fn(search);
    }, checkboxlist: function () {
        $("#grvNewCarOpportunity tr").each(function (i) {

            if ($(this).find("td").first().find("Input").attr("disabled")) {
                $(this).find("td").first().find(":checkbox").removeAttr("checked");
            }
        });
    }, isCheck: function () {
        //亚超登录判断
        if (WeakSuperLoginOperation()) preventDefault();

        //
        if ($("#grvNewCarOpportunity :checked[id!=grvNewCarOpportunity_AllCheckBox]").length > 0) {
            if (selectData.SetPrincipal && selectData.SetPrincipal.length) {
                $("#lbn_PrincipalList").text(selectData.SetPrincipal[0].Text);
                $("#hf_Principal").val(selectData.SetPrincipal[0].Value);
                $("#lbsetinfo").text("");
            }
            var ids = [], customerInfoIDs = [];
            $("#grvNewCarOpportunity :checked").parent("td").parent("tr").find("td:last a").each(function () {
                ids.push($(this).attr('realID'));
                customerInfoIDs.push($(this).attr('customerInfoID'));
            });
            $('#RealIDS').val(ids.join());
            $('#CustomerInfoIDS').val(customerInfoIDs.join());
            _M.Show('HiddenDIV', 'TitleDIV');
        } else {
            syncGetOrder.alert('请选择要分配的客户！', false);
            this.preventDefault();
        }
    }
    , SetPrintHref: function (obj) {
        //亚超登录判断
        if (WeakSuperLoginOperation()) return false;

        //双呼屏蔽
        var userName = $.trim($("#userName").val());
        var userPhone = $.trim($("#userPhone").val());
        var IntentionStage = $.trim($("#hf_IntentionStage").val());
        var AccountID = $.trim($("#hf_Account").val());
        var nexContactTime = $.trim($("#nexContactTime").val());
        var orderCars = $.trim($("#hf_SetCarId").val());
        var txtBeginTime = $.trim($("#txtBeginTime").val());
        var txtEndTime = $.trim($("#txtEndTime").val());
        var txtStartContactTime = $.trim($("#txtStartContactTime").val());
        var txtEndContactTime = $.trim($("#txtEndContactTime").val());
        var lostStart = $.trim($("#lostStart").val());
        var lostEnd = $.trim($("#lostEnd").val());
        var LostSerial = $.trim($("#hf_LostSerial").val());
        var curtype = $.trim($("#curType").val());

        var txtLeadCreateBeginTime = $.trim($("#txtLeadCreateBeginTime").val());
        var txtLeadCreateEndTime = $.trim($("#txtLeadCreateEndTime").val());

        var url = "print/PrintCustomersList.aspx?";


        url = url + "userName=" + userName + "&userPhone=" + userPhone + "&IntentionStage=" + IntentionStage
                + "&AccountID=" + AccountID + "&nexContactTime=" + nexContactTime + "&OrderCars=" + orderCars + "&txtBeginTime=" + txtBeginTime + "&txtEndTime=" + txtEndTime
                + "&txtStartContactTime=" + txtStartContactTime + "&txtEndContactTime=" + txtEndContactTime + "&lostStart=" + lostStart + "&lostEnd=" + lostEnd
                + "&LostSerial=" + LostSerial + "&curtype=" + curtype + '&LeadCreateBeginTime=' + txtLeadCreateBeginTime + '&LeadCreateEndTime=' + txtLeadCreateEndTime;

        $("#print").attr("href", url);
    }
    , setRemark: function () {
        var val = $.trim($('#remarkContext').val());
        if (!val) {
            syncGetOrder.alert('备注内容不能为空！', false);
            preventDefault();
        }
        if (val.length > 200) {
            syncGetOrder.alert('备注内容最多200字！', false);
            preventDefault();
        }
        //$(this.__currentRemarkObj).attr('remark', val);
        $('#HiddenRemarkDIV').css('display', 'none'); _M.Close();
    }
    //    , remark_Click: function (obj) {
    //        this.__currentRemarkObj = obj;
    //        $('#hf_realID').val($(obj).attr('reaID'));
    //        _M.Show('HiddenRemarkDIV', 'titleRemark');
    //        $('#remarkContext').text($(obj).attr('remark'));

    //    }
    , preventDefault: function () {

        var e = event || window.event;
        if (!e) {
            return;
        }

        // if preventDefault exists run it on the original event
        if (e.preventDefault) {
            e.preventDefault();
        }
        // otherwise set the returnValue property of the original event to false (IE)
        e.returnValue = false;
    }
    , GridViewMouseOut: function (obj, index) {
        $(obj).addClass('main_search');
    }
    , bindBlurFocusEvent: function () {
        $.each(['lineone', 'linetwo', 'lostfilter'], function (i, n) {
            $("#" + n).find('input[type=text],a[data_name]').bind('focus', function () {
                $(this).addClass('cur');
            })
             .bind('blur', function () {
                 $(this).removeClass('cur');
             });
        });
    }
    , isOverFlow: function (isCorrect) {
        if (isCorrect)
            $(window.document.body).css('overflow', "hidden");
        else
            $(window.document.body).removeAttr('style');

    },
    setRemarkHidden: function (value, remark) {
        //remark=remark.replace("\\n", "\n").replace("\\r\\n", "\r\n");
        $('#hf_realIDHidden').val(value); _M.Show('HiddenRemarkDIV', 'titleRemark'); $('#remarkContext').text(remark);
    }
};
/***************************************************************************************************************************************************************************************/
var DropDownInfo = {
        success:function (target,result) {
                DropDownList.IsLoaded = false;
                DropDownList.AjaxBindData($("#"+target), result);
       }
       ,AjaxLoadCarInfo: function AjaxLoadCarInfo(csId) {//加载车款信息数据
           var success=this.success;
           var res = cachePoolHelper.get('__AjaxLoadCarInfo' + csId);
           if(!res){
                $.ajax({
                    url: "ajaxLoad/AjaxRequest.aspx?op=GetCarsByDealerIdAndSerialIdOnly",
                    type: "post",
                    data: { DealerId: selectData.DealerID, csId: csId },
                    dataType: "json",
                    success:function(result){
                        success("lbn_SetCarName",result);
                        cachePoolHelper.add('__AjaxLoadCarInfo' + csId, result, 1000 * 60 * 3);
                    } 
                });
           }else
                success("lbn_SetCarName",res);
        }, AjaxLoadCarSerialsInfo: function AjaxLoadCarSerialsInfo(csId) {//加载车型信息数据
            var success=this.success;
            var res = cachePoolHelper.get('__AjaxLoadCarInfo' + csId);
            if(!res){
                $.ajax({
                    url: "ajaxLoad/AjaxRequest.aspx?op=GetSerialsByDealerIdAndBrandIdOnly",
                    type: "post",
                    data: { DealerId: selectData.DealerID, BrandId: csId },
                    dataType: "json",
                    success: function (result) {
                            success("lbn_SetCarSerials",result);
                            cachePoolHelper.add('__AjaxLoadCarInfo' + csId, result, 1000 * 60 * 3);
                        } 
                    });
            }else
                success("lbn_SetCarSerials",res);
            },
    InitSetSerialsDefault: function () {//设置车款默认显示信息
        tools.InitFunc("hf_SetCarSerials", DropDownInfo.SetCarSerialsText, function () {
            $("#hf_SetCarSerialsName").val("全部车型");
            $("#lbn_SetCarSerials").text("全部车型");
            $("#hf_SetCarSerials").val("-1");
        });
    },
    InitSetBrandsDefault: function () {
        var setCarBrands = $("#hf_SetCarBrands").val();
        if (!setCarBrands) {
            $("#lbn_SetCarBrands").text("全部品牌");
            $("#hf_SetCarBrands").val("-1");
        } else {
            DropDownInfo.SetCarBrandText();
        }
    },
    InitSetCarInfoDefault: function () {//设置车款默认显示信息
        tools.InitFunc("hf_SetCarId", DropDownInfo.SetCarInfoText, function () {
            $("#lbn_SetCarName").text("全部车款");
            $("#hf_SetCarId").val("-1");
            $("#hf_SetCarName").val("全部车款");
        });
    },
    SetCarSerialsText: function () {//设置车型显示信息
        //加载车型数据
        DropDownInfo.AjaxLoadCarSerialsInfo($("#hf_SetCarBrands").val());
        //初始化下拉显示信息
        $("#lbn_SetCarSerials").text($("#hf_SetCarSerialsName").val());
    },
    SetCarInfoText: function () {//设置车款显示信息
        //加载车款数据
        DropDownInfo.AjaxLoadCarInfo($("#hf_SetCarSerials").val());
        //初始化下拉显示信息
        $("#lbn_SetCarName").text($("#hf_SetCarName").val());
    },
    SetCarBrandText: function () {
        var setCarBrands = $("#hf_SetCarBrands").val();
        var datasourcelist = selectData.SetCarBrands;
        for (var s in datasourcelist) {
            if (datasourcelist[s].Value == $.trim(setCarBrands)) {
                $("#lbn_SetCarBrands").text(datasourcelist[s].Text);
                break;
            }
        }
    },
    CallBackIntentionStageText: function () {//意向阶段
        tools.initDefaultText("hf_IntentionStage", "SetIntentionStageSource", "lbn_IntentionStage");
    },
    CallBackLostSerialText: function () {
        tools.initDefaultText("hf_LostSerial", "SetLostSerial", "lbn_LostSerial");
    },
    CallBackAccountText: function () {
        tools.initDefaultText("hf_Account", "SetAccount", "lbn_AccountList");
    },
    CallBackPrincipalText: function () {
        tools.initDefaultText("hf_Principal", "SetPrincipal", "lbn_PrincipalList");
    },
    //这个方法会在dom加载完成后调用
    InitAll: function () {
        //初始化品牌默认值
        DropDownInfo.InitSetBrandsDefault();
        //初始化车型默认值
        DropDownInfo.InitSetSerialsDefault();
        //设置车款默认显示信息
        DropDownInfo.InitSetCarInfoDefault();
        //tools.bindBlurFocusEvent(); //查询选项的id
        //注册uploadpanel刷新要执行的事件
        tools.setCallbackMethods([DropDownInfo.CallBackIntentionStageText, DropDownInfo.CallBackLostSerialText, DropDownInfo.CallBackAccountText, DropDownInfo.CallBackPrincipalText, DropDownInfo.SetCarBrandText, DropDownInfo.SetCarSerialsText, DropDownInfo.SetCarInfoText, tools.changeCur, tools.bindBlurFocusEvent, IntentionStageHelper.clearCachePool, syncGetOrder.clearCachePool]); //
    }
};
/***************************************************************************************************************************************************************************************/
/*
 *  绑定回调函数
 */
if (selectData) {
    //添加事件
    selectData.SetIntentionStageSourcecallback = tools.getDropDownCallBack("hf_IntentionStage");
    selectData.SetLostSerialcallback = tools.getDropDownCallBack("hf_LostSerial");
    selectData.SetAccountcallback = tools.getDropDownCallBack("hf_Account");
    selectData.SetPrincipalcallback = tools.getDropDownCallBack("hf_Principal");
    //品牌
    selectData.SetCarBrandscallback = tools.getDropDownCallBack("hf_SetCarBrands", tools.getCarBrandCallBack("hf_SetCarSerials", "hf_SetCarSerialsName", "lbn_SetCarSerials", "SetCarSerials", "hf_SetCarId", "hf_SetCarName", "lbn_SetCarName", "SetCarInfo"));
    //车型选中回调
    selectData.SetCarSerialscallback = tools.getDropDownCallBack("hf_SetCarSerials", tools.getCarSerialsCallBack("hf_SetCarId", "hf_SetCarName", "lbn_SetCarName", "SetCarInfo", "hf_SetCarSerialsName"));
    //车款选中回调
    selectData.SetCarInfocallback = tools.getDropDownCallBack("hf_SetCarId", function (obj, data) {
        $("#hf_SetCarName").val(data.Text);
    });
}
/*
 *  异步加载订单对象 
 */

var syncGetOrder = (function ($, window, selectData, tools) {
    /*
    * get sync Order object
    */
    function SyncGetOrder(obj) {
        this.__doObj = null; //指向当前处理对象
        this.__tID = undefined; //二级tableid
        this.__tBody = null;
        this.__mainTBody = null;
        this.__params = { pageSize: 5, pageIndex: 0, dealerID: selectData.DealerID, realID: 0, IsUpdateIntentionStage: selectData.IsUpdateIntentionStage, depID: selectData.depId, totalCount: 0 };
        this.__getParams(obj);

        return this;
    }

    /**
    *  create manage object
    */
    var initManageObj = {
        cachePool: {},
        grayList: [],
        getManageInstance: function getManageInstance(obj) {
            //
            var id = $(obj).attr('customerinfoid');
            if (this.cachePool[id]) return this.cachePool[id];

            return this.cachePool[id] = new SyncGetOrder(obj);
        }
        , __getParams: function (obj) {
            this.__doObj = $(obj);
            this.__tID = this.__doObj.attr('tID');
            if (this.__tID)
                this.__tBody = $('#' + this.__tID).find('tbody');
            this.__params.pageIndex = this.__doObj.attr('pageIndex') || 0;
            this.__params.realID = this.__doObj.attr('realID');
            this.__params.customerInfoID = this.__doObj.attr('customerInfoID');
            this.__params.totalCount = this.__doObj.attr('totalCount') || 0;
            this.__params.hasCheckBoxColumn = $('#hasCheckBoxColumn').val();
            this.__params.isDelete = $('#isDeleteStatus').val();
            this.__params.AccountID = this.__doObj.attr('accountID'); //0; // 
            this.__params.isAdmin = selectData.isAdmin;
            this.__params.curType = $('#curType').val();
            this.__colCount = this.__getcolCount();

            this.__params.FollowStatus = this.__params.curType && this.__params.curType == '1' ? '1' : '-1';
            return this;
        }
        , __setParam: function (key, value) {
            if (!this.__doObj) throw new Error('getSyncOrder doObj object is null');
            this.__doObj.attr(key, value);
        }
        , clearCachePool: function () {
            this.cachePool = {};
            this.grayList = [];
        }
        , __getcolCount: function () {
            //是否流失标签
            if (this.__params.curType == selectData.curTypeArray[2])
                return "5";
            //市场全部标签
            if (this.__params.depID == 1 && this.__params.curType == selectData.curTypeArray[0])
                return "7";
            else if (this.__params.depID == 1)//其它返回6
                return "6";

            //其他登录人按照这个走
            return this.__params.hasCheckBoxColumn != 0 ? '8' : '7';
        }
    };
    /**
    *  dom opreate
    */
    var domOpreate = {
        __getHead: function () {
            return '<tr class="new_table_tr"><td colspan="' + this.__colCount + '" class="new_td"><table id="' + this.__tID + '" cellspacing="0" cellpadding="0"  style="border-width:0px;width:100%;"> <colgroup> ' + domOpreate.__getCol.call(this) + '</colgroup><tbody>';
        }
        , __getCol: function () {
            //流失标签
            if (this.__params.curType == selectData.curTypeArray[2])
                return '<col style="width:300px;"><col> <col> <col> <col style="width:50px;">';


            var colsBegin = '<col style="width:300px;">'
                , colsEnd = ' <col style="width:50px;">'
                , colCheck = this.__params.hasCheckBoxColumn == 1 ? '<col class="radio">' : ''
                , colMiddle
                , cols;

            switch (this.__colCount) {
                case '6':
                    colMiddle = colCheck ? 3 : 4;
                    break;
                case '7':
                    colMiddle = colCheck ? 4 : 5;
                    break;
                case '8':
                    colMiddle = colCheck ? 5 : 6;
                    break;
            }
            cols = colCheck + colsBegin;
            for (var i = 0; i < colMiddle; i++) {
                cols += '<col>';
            }

            return cols + colsEnd;
        }
        , __foot: ' </tbody></table></td></tr>'
        , __ToggleGray: function (obj) {
            if (!this.__mainTBody)
                this.__mainTBody = $(obj).parent().parent().parent(); //.find('tr[class=th]').find('th[class=last]')
            var a = this.__mainTBody.find('.gray');
            if (a && a.length > 0) {//全部折叠变灰
                a.each(function () {
                    $(this).removeClass('gray');
                });
            } else if (!this.__mainTBody.find('a[realid]').hasClass('down')) {//4 5
                if (initManageObj.grayList.length === 0) {
                    this.__mainTBody.find('.showGay').each(function () {
                        initManageObj.grayList.push($(this));
                    });
                    //this.__grayList.push(this.__mainTBody.find('th').eq(4));
                    //this.__grayList.push(this.__mainTBody.find('th').eq(5));
                }
                for (var i = 0, j = initManageObj.grayList.length; i < j; i++) {
                    initManageObj.grayList[i].addClass('gray');
                }
                //                this.__mainTBody.find('th').hasCalss('showGay').each(function () {
                //                    $(this).addClass('gray');
                //                });
            }
            return this;
        }
        , __slideToggle: function (obj) {
            if (!obj) return;
            $(obj).parent().parent().next('.new_table_tr').slideToggle(300);
            return this;
        }
        /*
        *向列表添加二级列表表结构
        */
        , __addTable: function (type, data) {
            var html;
            if (!this.__tID) {//do once
                this.__tID = this.__randomID();
                this.__setParam('tID', this.__tID); //写入处理a标签属性
                html = this.__getHead() + this.__foot;
                $(this.__doObj).parent().parent().after(html);
                this.__tBody = $('#' + this.__tID).find('tbody');
            }
            if (!type) return this;
            //根据type获取追加内容
            html = this.__getTrByType(type);
            this.__clearTypeTr();
            if (data) html = data + html;
            this.__tBody.append(html);

            return this;
        }
        , __getTrByType: function (type) {
            switch (type) {
                case this.__ACTIONTYPE.LOADING:
                    return '<tr tr_loading=""><td colspan="' + this.__colCount + '" class="being_loaded">正在加载...</td> </tr>';
                case this.__ACTIONTYPE.LOADMORE:
                    return '<tr tr_loadMore=""><td colspan="' + this.__colCount + '" class="being_loaded" style="cursor: pointer;" onclick="syncGetOrder.refresh(this)">加载更多...</td></tr>';
                case this.__ACTIONTYPE.LOADERROR:
                    return '<tr tr_loadError=""><td colspan="' + this.__colCount + '" class="fail_toload">加载失败，检查网络后再试<a href="javascript:void(0);"  onclick="syncGetOrder.refresh(this)" class="refresh">刷新</a></td> </tr>';
                default:
                    return '';
            }
        }
        , __clearTypeTr: function () {
            if (!this.__tBody) throw new Error('getSyncOrder tBody object is null');
            this.__tBody.find('tr').remove('tr[tr_loading]').remove('tr[tr_loadMore]').remove('tr[tr_loadError]');
        }
        , __randomID: function () {
            if (!Date.now) {
                Date.now = function now() {
                    return new Date().getTime();
                };
            }
            return Date.now().toString() + '_id';
        }

    };
    /**
    *  create ajax object
    */
    var ajaxObj = {
        __ajaxGetSyncOrder: function () {
            ++this.__params.pageIndex;
            //this.__setParam('pageIndex', ++this.__params.pageIndex);
            var syncGetOrder = this;
            $.ajax({
                url: "ajaxLoad/GetCustomerOrdersSync.ashx",
                type: "post",
                data: syncGetOrder.__params,
                dataType: "json",
                success: function (result) {
                    var html = '', type = -1;
                    if (result && result.resCode === 1) {/*{resCode:1,data:'',totalCount:10} */
                        html = result.data;
                        if (html) {
                            syncGetOrder.__params.totalCount = result.totalCount;
                            //syncGetOrder.__setParam('totalCount', ++syncGetOrder.__params.totalCount);
                            if (syncGetOrder.__params.pageIndex * syncGetOrder.__params.pageSize < result.totalCount) {
                                type = syncGetOrder.__ACTIONTYPE.LOADMORE;
                            }
                        } else {
                            opreate.alert('未获取到数据', false);
                        }
                    } else {
                        type = syncGetOrder.__ACTIONTYPE.LOADERROR;
                        syncGetOrder.__params.pageIndex--;
                    }
                    //将获取到的内容插入表格
                    syncGetOrder.__addTable(type, html);
                }
                , error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                    //将获取到的内容插入表格
                    syncGetOrder.__addTable(syncGetOrder.__ACTIONTYPE.LOADERROR);
                    syncGetOrder.__params.pageIndex--;
                }
            });
            return syncGetOrder;
        }
    };

    /**
    *  opreate object
    */
    var opreate = {
        getSyncOrderClick: function (obj) {
            var flag = $(obj).attr('isLoaded');
            this.__slideToggle(obj);
            //切换显示
            tools.SetUpDown(obj);
            this.__ToggleGray(obj);

            if (flag) return; //下拉之后不再进行加载，屏蔽事件
            this.__getSyncOrder(obj).__setParam('isLoaded', 'true');
        }
        , __getSyncOrder: function (obj, type) {

            //this.__getParams(obj);
            if (this.__params.pageIndex > 0 && this.__params.pageIndex * this.__params.pageSize >= this.__params.totalCount) return this; //已加载完不再加载

            return this.__addTable(this.__ACTIONTYPE.LOADING).__ajaxGetSyncOrder(); //发送异步请求

        }
        /*
        @param isCorrect Boolean 成功失败
        */
        , alert: function (msg, isCorrect) {
            if (isCorrect)
                window._M.TitMsg(msg, 'BitDoMsg');
            else
                window._M.Check(msg, 'BitCheckMsg');
        }
    };
    /*
    * base Class
    */
    var syncGetOrderBase = {
        __getHead: domOpreate.__getHead
        , __foot: domOpreate.__foot
        , __ajaxGetSyncOrder: ajaxObj.__ajaxGetSyncOrder
        , __getSyncOrder: opreate.__getSyncOrder
        , __ToggleGray: domOpreate.__ToggleGray
        , __slideToggle: domOpreate.__slideToggle
        /*
        *向列表添加二级列表表结构
        */
        , __addTable: domOpreate.__addTable
        , __getTrByType: domOpreate.__getTrByType
        , __clearTypeTr: domOpreate.__clearTypeTr
        , __ACTIONTYPE: {
            LOADING: 1,
            LOADMORE: 2,
            LOADERROR: 3
        }
        , __randomID: domOpreate.__randomID
        , __getParams: initManageObj.__getParams
        , __setParam: initManageObj.__setParam
        , __getcolCount: initManageObj.__getcolCount

        , getSyncOrderClick: opreate.getSyncOrderClick
    };

    SyncGetOrder.prototype = syncGetOrderBase;
    /*
    *  public object
    */
    return {
        getSyncOrderClick: function (obj) {
            initManageObj.getManageInstance(obj).getSyncOrderClick(obj);
        },
        refresh: function (obj) {
            initManageObj.getManageInstance($(obj).parents('tr[class=new_table_tr]').prev().find('a[tid]')[0]).__getSyncOrder(obj);
        },
        alert: opreate.alert,
        clearCachePool: function () {
            initManageObj.clearCachePool();
        }
    };

})($, window, selectData, tools);

/***************************************************************************************************************************************************************************************/
/*
 *  异步更新意向阶段
 */
var IntentionStageHelper = (function ($, window, selectData, tools) {
    /*
    * get sync Order object
    */
    function IntentionStage(obj) {
        this.__timer = null;
        this.__IntentionStageParams = { DealerId: selectData.DealerID };
        this.__actionObj = null;
        this.__notFollowLeadCount = 0;
        this.__getParams($(obj));
        this.__isSend = false;

        return this;
    }
    /**
    *  create manage object
    */
    var initManageObj = {
        cachePool: {},
        getManageInstance: function getManageInstance(obj) {
            //
            var id = typeof obj === 'object' ? $(obj).attr('orderid') : obj;
            if (this.cachePool[id]) return this.cachePool[id];

            return this.cachePool[id] = new IntentionStage(obj);
        }
        , clearCachePool: function () {
            this.cachePool = {};
        }
    };
    IntentionStageBase = {
        __getParams: function ($obj) {
            this.__IntentionStageParams.orderId = $obj.attr('orderId');
            this.__IntentionStageParams.LeadType = $obj.attr('LeadType');
            this.__IntentionStageParams.AccountID = $obj.attr('AccountID');
            this.__IntentionStageParams.orderCreateTime = $obj.attr('orderCreateTime');
            this.__IntentionStageParams.fistFollowTime = $obj.attr('fistFollowTime');
            this.__actionObj = $obj;

            var parent = $obj.parents('tr[class=new_table_tr]').prev().find('a[notFollowCount]');
            this.__notFollowLeadCount = parent.attr('notFollowCount') || 0;
            this.__IntentionStageParams.CustomerInfoID = parent.attr('customerInfoID');
        }
        , __setParams: function (key, value) {
           var parent= this.__actionObj.parents('tr[class=new_table_tr]').prev().find('a[notFollowCount]');
           if(parent)
               parent.attr(key, value)
        }
        , __getSpan: function (epNum) {
            var res = this.find('td').eq(epNum).find('span');
            if (!res || res.length === 0)
                return undefined;
            return res;
        }
        , bindIntentionStage: function (obj) {

            if (window.WeakSuperLoginOperation()) return false;

            var $obj = $(obj),
                intentionStage = $obj.attr("IntentionStage");

            $('#menuIntentionStage').attr("orderid", $obj.attr('orderid'));

            $("#menuIntentionStage li").each(function (index) {
                if ($(this).attr("v") == intentionStage) {
                    $(this).attr("class", "is_selected");
                } else {
                    $(this).attr("class", "");
                }
            });

            this.__actObj = $obj;
            this.IntentionStage_onclick($obj.attr('intentionStage'), true); //显示当前意向阶段
            this.__getParams($obj);

            _M.Show('HiddenIntentionStageDiv', 'TitleIntentionStageDiv');
        }
        , __ajaxGetFollowStatus: function () {
            var cur = this;
            //            if (cur.__timer) { clearTimeout(cur.__timer); cur.__timer = null; }
            if (cur.__notFollowLeadCount > 0) return;


            $.ajax({
                url: "ajaxLoad/AjaxRequest.aspx?op=GetCustomerFollowStatus",
                type: "post",
                data: { infoID: cur.__IntentionStageParams.CustomerInfoID },
                dataType: "json",
                success: function (result) {
                    //clear timer

                    if (result && result.ResultStatus > 0) {
                        var tr = cur.__actionObj.parents('tr[class=new_table_tr]').prev(),
                            spanFollow = IntentionStageBase.__getSpan.call(tr, 1) || IntentionStageBase.__getSpan.call(tr, 2);

                        //更新跟进状态
                        if (spanFollow) {
                            if (result.FollowStatus === 0) {
                                spanFollow.removeClass('state_blue');
                                spanFollow.addClass('state_yellow');
                            } else {
                                spanFollow.removeClass('state_yellow');
                                spanFollow.addClass('state_blue');
                            }
                        }
                        //更新最后跟进时间
                        if (result.LastFollowTim && result.LastFollowTim !== '1900/1/1 0:00:00') {
                            var lastTimeSpan = tr.find('td').eq(1).find('span');


                            if (lastTimeSpan) lastTimeSpan.text(result.LastFollowTime);

                        }
                    }
                }
            });
        }
        , IntentionStage_onclick: function (intentionStage, virtual) {
            var cur = this;
            this.__IntentionStageParams.IntentionStage = intentionStage;
            if (!virtual)
                this.__actObj.attr("IntentionStage", intentionStage);

            if (intentionStage != "") {
                $("#menuIntentionStage li").each(function (index) {
                    if ($(this).attr("v") == intentionStage) {
                        $(this).attr("class", "is_selected");
                        cur.__IntentionStageParams.IntentionStageText = $.trim($(this).find('a').text());

                    }
                    else
                        $(this).attr("class", "");
                });
            }
        }
        , ajaxUpdateIntentionStage: function () {
            var cur = this;

            if (this.__isSend) {
                syncGetOrder.alert('操作已发送，请稍等片刻！', false);
                return false;
            }
            this.__isSend = true;
            //            setTimeout(function () { alert(cur.__IntentionStageParams.orderId); }, 1500);
            //            return;


            $.ajax({
                url: "ajaxLoad/AjaxRequest.aspx?op=ajaxUpdateIntentionStage",
                type: "post",
                data: cur.__IntentionStageParams,
                dataType: "json",
                success: function (result) {
                    cur.__isSend = false;
                    if (result && result.ResultStatus > 0) {
                        syncGetOrder.alert('操作成功！', true);
                        var parent = cur.__actionObj.parent().parent(),
                        span = IntentionStageBase.__getSpan.call(parent, 2) || IntentionStageBase.__getSpan.call(parent, 1),
                        textSpan = IntentionStageBase.__getSpan.call(parent, 5) || IntentionStageBase.__getSpan.call(parent, 4),
                        lastFollowSpan = IntentionStageBase.__getSpan.call(parent, 0) || IntentionStageBase.__getSpan.call(parent, 1);
                        if (textSpan) { textSpan.text(cur.__IntentionStageParams.IntentionStageText); }

                        if (span) {

                            span.removeClass();
                            //state state_blue
                            span.attr('class', result.objFollowStatusCss);
                            span.text(result.objFollowStatusText);
                        }
                        if (result.LastFollowTime && result.LastFollowTime !== '1900/1/1 0:00:00') {
                            if (lastFollowSpan) lastFollowSpan.text('最后联系时间：' + result.LastFollowTime);
                        }
                        IntentionStageBase.__setParams.call(cur, 'notFollowCount', --cur.__notFollowLeadCount);
                        cur.__timer = setTimeout(function () { cur.__ajaxGetFollowStatus(); }, 150);
                    } else
                        syncGetOrder.alert('操作失败,请稍后重试！', false);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {


                }
            });
        }
    };
    IntentionStage.prototype = IntentionStageBase;
    return {
        bindIntentionStage: function (obj) {
            initManageObj.getManageInstance(obj).bindIntentionStage(obj);
        },
        IntentionStage_onclick: function (intentionStage) {
            initManageObj.getManageInstance($('#menuIntentionStage').attr("orderid")).IntentionStage_onclick(intentionStage);
        },
        ajaxUpdateIntentionStage: function () {
            initManageObj.getManageInstance($('#menuIntentionStage').attr("orderid")).ajaxUpdateIntentionStage();
        },
        clearCachePool: function () {
            initManageObj.clearCachePool();
        }
    };

})($, window, selectData, tools);
/***************************************************************************************************************************************************************************************/
/*
 *  下次联系时间设置时间规则限制
 */
var datePicker = {
    __createOption: function ($curEl, $target, type) {
        switch (type) {
            case this.__OPTHIONTYPE.START:
                //console.log("create start");
                return function () {
                    WdatePicker({
                        dateFmt: 'yyyy-MM-dd HH:mm', minDate: '%y-%M-%d', isShowToday: true, isShowClear: true, isShowOK: true, onpicked: function () { $curEl.attr("isLoaded", "true"); }, oncleared: function () { $target.val(''); }
                    });
                };
            case this.__OPTHIONTYPE.END:
                //console.log("create end");
                return function () {
                    var date1 = $.trim($target.val()),
                        drection = datePicker.__direction === datePicker.__DRIECTIONTYPE.RIGHT;
                        date1 = date1.replace(new RegExp('-', "gm"), '/'); //兼容IE8.0.时间格式进行转换

                    WdatePicker({
                        dateFmt: 'yyyy-MM-dd HH:mm', minDate: !date1 ? '%y-%M-%d' : drection ? datePicker.__getRightMinDate(date1) : datePicker.__getMinDate(date1), maxDate: !date1 ? '' : drection ? datePicker.__getRightMaxDate(date1) : datePicker.__getMaxDate(date1), isShowToday: true, isShowClear: true, isShowOK: true, onpicked: function () { $curEl.attr("isLoaded", "true"); }, oncleared: function () { $target.val(''); }
                    });
                };
        }
    }
    , focus: function (curEl) {
        if (!curEl) return Function.prototype; //throw new Error('param is error!'); !(curEl instanceof Object) 这种写法IE8不兼容，不合适


        if (!curEl.hasAttribute || !curEl.hasAttribute('date_picker')) return Function.prototype;
        if (!curEl.hasAttribute || !curEl.hasAttribute('bind_to')) return Function.prototype; //throw new Error('The method focus need bind_to Attribute!');

        var $curEl = $(curEl),
            $target = $('#' + $curEl.attr('bind_to')),
            idStr = $curEl.attr('id'),
            isLoaded = $.trim($curEl.attr('isLoaded')) === 'true',
            start = $.trim($curEl.val()) === "",
            end = $.trim($target.val()) === "";
        //console.log("-----------------------------------------------------------");
        //console.log(curEl, isLoaded, start, end);

        this.__stopEventBubble();

        if (start && end) {
            //console.log("clear");
            //this.__direction = null; //清空
            $curEl.attr("isLoaded", "false");
        }
        //console.log(this.__direction);
        if (!isLoaded) {
            //console.log("loaded");
            if (!this.__direction) {
                this.__direction = $curEl.attr('date_picker') === 'left' ? this.__DRIECTIONTYPE.LEFT : this.__DRIECTIONTYPE.RIGHT;
                if (this.__direction === this.__DRIECTIONTYPE.RIGHT) {
                    alert('请先选择起始时间段！');
                    this.__direction = null;
                    return;
                }
            }

            //重置
            this.__elments[idStr] = this.__createOption($curEl, $target, this.__direction === ($curEl.attr('date_picker') === 'left' ? this.__DRIECTIONTYPE.LEFT : this.__DRIECTIONTYPE.RIGHT) ? this.__OPTHIONTYPE.START : this.__OPTHIONTYPE.END);
            return this.__elments[idStr];
        } else
            return this.__elments[idStr];
    }
    , //阻止事件冒泡
    __stopEventBubble: function (event) {
        var e = event || window.event;
        if (!e) return;
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        e.cancelBubble = true;
    }
    , __OPTHIONTYPE: {
        START: 1,
        END: 2
    }
    , __DRIECTIONTYPE: {
        LEFT: 1,
        RIGHT: 2
    }
    , __getEl: function (selector) {
        return document.getElementById(selector);
    }
    , init: function () {
        var arry = $('input[date_picker]');
        if (!arry || arry.length === 0) throw new Error('param is not a Array Object');
        arry.each(function () {
            var el = $(this);
            el.bind('click', function (event) {
                datePicker.focus(el[0])();
                event.stopPropagation();
            });

        });
    }
    , __elments: {}
    , __direction: null//1为从左向右选、2为从右向左选
    , __getRightMinDate: function (dateStr) {
        return this.__getDate(dateStr, function (date) {
            return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + (date.getDate()) + ' 00:00:00';
        });
    }
    , __getRightMaxDate: function (dateStr) {
        return this.__getDate(dateStr, function (date) {
            return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + (date.getDate()) + ' ' + date.getHours() + ':' + (date.getMinutes() - 10);
        });
    }
    , __getMaxDate: function (dateStr) {
        return this.__getDate(dateStr, function (date) {
            return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + (date.getDate()) + ' 23:59:59';
        });
    }
    , __getMinDate: function (dateStr) {
        return this.__getDate(dateStr, function (date) {
            return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + (date.getDate()) + ' ' + date.getHours() + ':' + (date.getMinutes() + 10);
        });
    }
    , __getDate: function (dateStr, fn) {
        if (!$.trim(dateStr)) return '';
        var date = new Date(dateStr);
        return fn(date);
    }
};
/*
 *  保存弹层状态，取消恢复数据内容
 */ 
/*
*  construcor
*/
function LayerData(target){
    this.texts=this.radios=this.checkBoxs=this.selects={};
    this.target=target;//弹层ID
    this.init();
    return this;
}       
/*
* init source data （使用需要标记dataMember属性）
*/
LayerData.prototype.init=function(){
    if(!this.target) throw new Error('[LayerData.setInputs] target param is undefined');

    var texts=this.texts,
        radios=this.radios,
        checkBoxs=this.checkBoxs,
        selects=this.selects,
        name,id,checked;

    $('#' + this.target).find('input[dataMember],a[dataMember]').each(function () {
            var obj=$(this);
            id=obj.attr('id'),
            checked=obj.attr('checked');
            //if(!obj.attr('dataMember')) return;//标记属性
            if(obj.is('input')){
                name=obj.attr('name');
                
                switch(obj.attr('type')){
                    case 'text':
                        texts[id]=obj.val();    
                        break;
                    case 'radio':
                        if(!radios.hasOwnProperty(name))
                            radios[name]={};
                        radios[name][id]=checked;         
                        break;
                    case 'checkBox':
                        checkBoxs[obj.attr('index')+'_index']=checked; 
                        break;
                }
            }
            else if(obj.is('a')){
                    if(!selects.hasOwnProperty(id))
                            selects[id]={};

                    selects[id]['linkVal']=obj.text();
                    selects[id]['hiddenVal']=obj.next('input[type=hidden]').val();
            }
        });
};
/*
* cancel event
*/
LayerData.prototype.cancel = function () {
    if (!this.target) throw new Error('[LayerData.cancel] target param is undefined');

    var texts = this.texts,
        radios = this.radios,
        checkBoxs = this.checkBoxs,
        selects = this.selects,
        name;
    $('#' + this.target).find('input[dataMember],a[dataMember]').each(function () {
        var obj = $(this);
        id = obj.attr('id');
        if (obj.is('input')) {
            name = obj.attr('name');
            switch (obj.attr('type')) {
                case 'text':
                    obj.val(texts[id]);
                    break;
                case 'radio':
                    obj.attr('checked', radios[name][id]);
                    break;
                case 'checkBox':
                    obj.attr('checked', checkBoxs[obj.attr('index') + '_index']);
                    break;
            }
        }
        else if (obj.is('a')) {
            obj.text(selects[id]['linkVal']);
            obj.attr('value', selects[id]['hiddenVal']);
            obj.next('input[type=hidden]').val(selects[id]['hiddenVal'])
        }
    });
};

/***************************************************************************************************************************************************************************************/
var cachePoolHelper = (function (window) {
    var cachePool = {
        limitation: 0//时效，毫秒
        /*
        * 添加到缓存池 
        * @param limitation 自定义优先级最高的时效
        */
        , add: function add(key, value, limitation) {
            this.__pool.objects[key] = value;
            //加时间戳  每次刷新时间戳 key不存在，或者没有timespan
            if (!this.__pool.objects[key] || !this.__pool.timeSpans[key])//一个缓存对象只创建一个时间戳对象。
                this.__pool.timeSpans[key] = new TimeSpan(limitation || this.limitation, !limitation);
            else
                this.__pool.timeSpans[key].init(limitation || this.limitation);
        }
        /*
        * 移除缓存 
        */
        , remove: function remove(key) {
            return (delete this.__pool.objects[key]) && (delete this.__pool.timeSpans[key]);
        }
        , get: function get(key) {
            if (this.__pool.objects[key]&&this.__pool.timeSpans[key].getIsActive())
                return this.__pool.objects[key];
            else
                return null;
        }
        /**
        * 如果设置了自己的时效，isOwn属性将为true，在重新设置全局对象的时候，可以选择不刷新优先级最高的。
        */
        , setLimitation: function (limitation, freshOwn) {
            this.limitation = limitation;
            for (var i in this.__pool.timeSpans) {
                if (freshOwn)
                    this.__pool.timeSpans[i].init(limitation);
                else if (!this.__pool.timeSpans[i].isOwn)
                    this.__pool.timeSpans[i].init(limitation);
            }
        }
        , __pool: {
            objects: {},
            timeSpans: {}
        }
    }
    function TimeSpan(limitation, isOwn) {

        this.init(limitation, isOwn);
        return this;
    }
    TimeSpan.prototype.getIsActive = function () {
        return this.timeBegin === this.timeEnd || this.timeEnd > Date.now();
    }
    TimeSpan.prototype.init = function (limitation, isOwn) {
        /*
        * IE 兼容
        */
        if (!Date.now) {
            Date.now = function now() {
                return new Date().getTime();
            };
        }
        this.isOwn = isOwn;
        this.limitation = limitation;
        this.timeBegin = Date.now();
        this.timeEnd = this.timeBegin + limitation;
    }
    return {
        get: function (key) {
            return cachePool.get(key);
        },
        add: function (key, value, limitation) {
            return cachePool.add(key, value, limitation);
        },
        remove: function (key) {
            return cachePool.remove(key);
        },
        setLimitation: function (limitation, freshOwn) {
            return cachePool.setLimitation(limitation, freshOwn || false);
        }
    };
})(window);
/***************************************************************************************************************************************************************************************/
/*
 *  Extend
 */ 

